package com.xiaoluo.web.k8;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xiaoluo.cd.entity.base.Servers;
import com.xiaoluo.common.enums.ServerTypeEnum;
import com.xiaoluo.service.KubernetesService;
import com.xiaoluo.service.ServerService;
import com.xiaoluo.web.BaseController;
import com.xiaoluo.web.form.KubeServiceForm;
import com.xiaoluo.web.form.ResultForm;
import com.xiaoluo.web.form.TreeNode;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Project : SpiderManager
 * Package : com.xiaoluo.web
 * Created by Willian.
 * Date  : 2015/10/21 20:29.
 */
@Controller
@RequestMapping("/k8")
public class K8Controller extends BaseController{
    private final static Logger logger = LoggerFactory.getLogger(K8Controller.class);

    @Autowired
    private ServerService serverService;
    @Autowired
    private KubernetesService kubernetesService;

    @RequestMapping(value = "/")
    public  String index(ModelMap model,String type){

        PodList pods = kubernetesService.getClient().pods().list();
        model.addAttribute("pods",pods);
        model.addAttribute("type",type);
        return "k8/index";
    }
    @RequestMapping(value = "/ns")
    public  String ns(ModelMap model,String type){
        NamespaceList ns = kubernetesService.getClient().namespaces().list();
        model.addAttribute("namespaces",ns);
        model.addAttribute("type",type);
        return "k8/namespaces";
    }
    @RequestMapping(value = "/list")
    public  String list(ModelMap model,String type,String namespace){

        try {
            List<KubeServiceForm> serviceList = kubernetesService.findServices(ServerTypeEnum.valueOf(type),namespace);
            model.addAttribute("services",serviceList);
        }catch (Exception e){
            e.printStackTrace();
        }

        model.addAttribute("type",type);
        model.addAttribute("namespace",namespace);
        return "k8/list";
    }

    @RequestMapping(value = "/services")
    public  String services(ModelMap model,String type){

        ServiceList serviceList = kubernetesService.getClient().services().list();
        model.addAttribute("services",serviceList);
        model.addAttribute("type",type);
        return "k8/services";
    }
    @RequestMapping(value = "/controllers")
    public  String controllers(ModelMap model,String type){
        ReplicationControllerList controllerList = kubernetesService.getClient().replicationControllers().list();
        model.addAttribute("controllerList",controllerList);
        model.addAttribute("type",type);
        return "k8/controllers";
    }
    @RequestMapping(value = "/viewTree")
    @ResponseBody
    public String viewTree(ModelMap model,@RequestParam(value = "type",defaultValue = "pods") String type){

        List<TreeNode> nodes = new ArrayList<TreeNode>();
        TreeNode namespaces = new TreeNode("Namespaces",null,"/k8/ns?type=ns",type.equals("ns"));
        TreeNode pods = new TreeNode(" Pods","fa fa-cubes","/k8/?type=pods",type.equals("pods"));
        TreeNode services = new TreeNode(" Services","fa fa-cloud","/k8/services?type=services",type.equals("services"));
        TreeNode controllers = new TreeNode(" Controllers","fa fa-th","/k8/controllers?type=controllers",type.equals("controllers"));
        TreeNode clients = new TreeNode("Nodes",null,"/k8/nodes",false);

        List<TreeNode> nsChilds = new ArrayList<TreeNode>();
                        nsChilds.add(pods);
                        nsChilds.add(services);
                        nsChilds.add(controllers);
        namespaces.setNodes(nsChilds);


        NodeList nodeList = kubernetesService.getClient().nodes().list();
        List<TreeNode> ndChilds = new ArrayList<TreeNode>();
        if(nodeList != null && nodeList.getItems()!= null){
            for(Node node :nodeList.getItems()){
                TreeNode tempTreeNode = new TreeNode(" "+node.getMetadata().getName(),"fa fa-server","/k8/node",false);
                ndChilds.add(tempTreeNode);
            }
        }

        clients.setNodes(ndChilds);
        nodes.add(namespaces);
        nodes.add(clients);


        return JSON.toJSONString(nodes, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping(value = "/viewNodes",method = RequestMethod.GET)
    @ResponseBody
    public ResultForm viewNodes(ModelMap model,String namespace,String name){

        ResultForm result = new ResultForm(0,"sucessed");

        if(name !=null && !"".equals(name)){
            result.setData(kubernetesService.getClient().nodes());
        }

        return result;
    }
    /*
    @RequestMapping(value = "/savePod",method = RequestMethod.GET)
    public  String savePod(ModelMap model,
                           String name,String namespace,String node,String dnsPolicy,
                           String container,String image,String pullPolicy,String protocol,
                           Integer hostPort,Integer containerPort,String phase){
        EditablePod  pb = new PodBuilder()
                .withNewMetadata()
                    .withName(name).withNamespace(namespace)
                    .withUid(UUID.randomUUID().toString()).withSelfLink(UUID.randomUUID().toString())
                .endMetadata()
                .withNewSpec()
                    .withNodeName(node).withDnsPolicy(dnsPolicy)
                    .withContainers()
                        .addNewContainer()
                        .withName(container)
                        .withImage(image)
                        .withTerminationMessagePath("/dev/termination-log")
                        .withImagePullPolicy(pullPolicy)
                        .withPorts()
                            .addNewPort()
                            .withProtocol(protocol)
                            .withHostPort(hostPort)
                            .withContainerPort(containerPort)
                        .endPort()
                    .endContainer()
                .endSpec()
                .withNewStatus()
                    .withPhase(phase)
                .endStatus().build();

        kubernetesClient.pods().create(pb);
        return "forward:/server/";
    }
    */
    //

}
